package cn.doctorpda.conference.ui.personal.dialog;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import cn.doctorpda.conference.MyApplication;
import cn.doctorpda.conference.R;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.UpdataInfo;
import cn.doctorpda.conference.event.UpdateMsg;
import cn.doctorpda.conference.okhttp.OkHttpUtils;
import cn.doctorpda.conference.okhttp.callback.FileCallBack;
import cn.doctorpda.conference.presenter.LogoutPresent;
import cn.doctorpda.conference.presenter.UpdateVersionPresenter;
import cn.doctorpda.conference.utils.AppUtils;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.utils.StringUtils;
import cn.doctorpda.conference.utils.T;
import cn.doctorpda.conference.view.callbackview.IBaseView;
import cn.doctorpda.conference.view.callbackview.IUpdateView;
import okhttp3.Call;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 */
public class SystemSettingDialogFragment extends DialogFragment implements
        OnClickListener, IBaseView<Msg>, IUpdateView {

    private FragmentActivity mActivity;
    private LogoutPresent present;
    private UpdateVersionPresenter updatePresenter;
    private OnLogout2Listener listener;
    private TextView tv_version;

    public void setLogout2Listener(OnLogout2Listener listener) {
        this.listener = listener;
    }

    @Override
    public void setUpdateInfo(final UpdataInfo info) {

        L.d("手动升级" + info.getVersion_code() + "本地版本" + AppUtils.getVersionCode(MyApplication.getInstance()));
        this.dismiss();
        if (AppUtils.getVersionCode(MyApplication.getInstance()) < info.getVersion_code()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("提示升级");
            builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    // TODO Auto-generated method stub
                    //进入主页面
//                    enterHome();
                    dialog.dismiss();
                }
            });
            builder.setMessage(info.getChangelog());
            builder.setPositiveButton("后台下载", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
//                    enterHome();
                    OkHttpUtils.get()
                            .url(info.getFilepath())
                            .build()
                            .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ConferenceDown", "conference.apk") {
                                @Override
                                public void inProgress(float progress, long total) {
                                    if (progress == 1.0) {
                                        installAPK("post");
                                    }
                                }

                                @Override
                                public void onError(Call call, Exception e) {

                                }

                                @Override
                                public void onResponse(File response) {
                                    L.d("onResponse");
//                                    installAPK(response);
                                }
                            });

                }
            });
            builder.setNegativeButton("下次再说", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });
            builder.show();
        }


    }

    private void installAPK(String msg) {
        EventBus.getDefault().post(new UpdateMsg(msg));
        /*Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.parse(t), "application/vnd.android.package-archive");
        getActivity().startActivity(intent);*/
    }

    @Override
    public void setUpdateError(Call call, Exception e) {
        T.showShort(getContext(), "检测信息失败请稍后再试");
    }

    public interface OnLogout2Listener {
        void setLogout2Listener(Msg msg);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mActivity = getActivity();
        View inflate = inflater.inflate(R.layout.fragment_system_setting, null);

        inflate.findViewById(R.id.btn_logout).setOnClickListener(this);
        inflate.findViewById(R.id.btn_upgradate).setOnClickListener(this);
        inflate.findViewById(R.id.btn_about_us).setOnClickListener(this);
        inflate.findViewById(R.id.btn_close).setOnClickListener(this);
        tv_version = (TextView) inflate.findViewById(R.id.tv_app_version);

//        String Ver = StringUtils.formatInt(Integer.valueOf(AppUtils.getVersionCode(MyApplication.getInstance())));
        tv_version.setText("V" + AppUtils.getVersionName(getActivity()));

        getDialog().getWindow().setBackgroundDrawable(
                new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
//        getDialog().setCanceledOnTouchOutside(false);

        present = new LogoutPresent(this);

        return inflate;
    }

    @Override
    public void onClick(View v) {
//        dismiss();
        switch (v.getId()) {
            case R.id.btn_logout:
                present.logout();
this.dismiss();
                break;
            case R.id.btn_upgradate:
                updatePresenter = new UpdateVersionPresenter(this);
//                String clientId = ClientInfo.getClientId(getActivity());
                updatePresenter.getUpdataInfo();
                break;
            case R.id.btn_about_us:

                break;
            case R.id.btn_close:
                this.dismiss();
                break;
            default:
                break;
        }
    }


    @Override
    public void setResult(Msg msg, Msg data) {

        listener.setLogout2Listener(msg);
    }

    @Override
    public void setError(Call call, Exception e) {

    }
}